const express = require('express')
const bookModule = require('../db/modules/book')

const router = express.Router()

const headerMiddleware = (req, res, next) => {
  res.header('content-type', 'text/html;charset=utf-8')
  res.header('access-control-allow-origin', '*')
  res.header('access-control-allow-headers', '*')
  res.header('access-control-allow-methods', '*')
  next()
}

router.get('/book', headerMiddleware, (req, res) => {
  res.setHeader('Content-Type', 'text/html;charset=utf-8')
  bookModule.find().then(data => {
    res.send(data)
  }).catch(error => {
    res.status(500).send('查询失败')
  })
})

router.get('/book/:id', headerMiddleware, (req, res) => {
  bookModule.findOne({ _id: req.params.id }).then(data => {
    res.send(data)
  }).catch(error => {
    res.status(500).send('查询失败')
  })
})

router.options('/book', headerMiddleware, (req, res) => {
  res.send('OK')
})
router.post('/book', headerMiddleware, (req, res) => {
  bookModule.insertOne(req.body).then(data => {
    res.send(data)
  }).catch(error => {
    res.status(500).send(`新增失败：${error}`)
  })

  // let postData = ''
  // req.on('data', chunk => {
  //   postData += chunk.toString()
  // })
  // req.on('end', () => {
  //   postData = JSON.parse(postData)
  //   bookModule.insertOne(postData).then(data => {
  //     res.send(data)
  //   }).catch(error => {
  //     res.status(500).send(`新增失败：${error}`)
  //   })
  // })
})

router.options('/book/:id', headerMiddleware, (req, res) => {
  res.send('OK')
})
router.put('/book/:id', headerMiddleware, (req, res) => {
  bookModule.updateOne({ _id: req.params.id }, req.body).then(data => {
    res.send(data)
  }).catch(error => {
    res.status(500).send('更新失败')
  })
})

router.delete('/book/:id', headerMiddleware, (req, res) => {
  bookModule.findOne({ _id: req.params.id }).then(data => {
    if(data && data.is_raw) {
      res.status(500).send('原始数据不能删除')
      return
    }
    bookModule.deleteOne({ _id: req.params.id, is_raw: { $ne: true }}).then(data => {
      res.send(data)
    }).catch(error => {
      res.status(500).send('删除失败')
    })
  }).catch(error => {
    res.status(500).send('删除失败')
  })
})

module.exports = router